import os
from constant.info import *


def open_file(path):
    with open(path, 'r', encoding='utf-8') as f:
        content_list = f.readlines()
        return content_list


def split_handler(target_list, need_handler_info_type):
    header_dict = {}
    header_list = []
    for v in target_list:
        t = v.strip('\n').split('\t')
        if len(t) > 1:
            k, v = t
            if not k:
                continue
        else:
            k = t[0]
            v = ''
        if need_handler_info_type == 'comm_query':
            header_list.append('{}={}'.format(k, v))
        else:
            header_dict[k] = v
    else:
        r = header_list if need_handler_info_type == 'comm_query' else header_dict
    return r


def file_path(file_name):
    main_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'file')
    if not file_name.startswith('common'):
        main_path = os.path.join(main_path, 'querys')
    return os.path.join(main_path, file_name)


def get_dict(dType):
    """主方法"""
    fp_dict = {
        'comm_header': file_path('common_header'),
        'comm_query': file_path('common_query'),
        'form': file_path('form'),
    }
    if dType not in fp_dict:
        return 404
    target_list = open_file(fp_dict[dType])
    return split_handler(target_list, dType)


class RequestInfo:
    def __init__(self, api, params_file_name=None):
        self.api = api
        self.params_file_name = params_file_name
        self.comm_query = get_dict('comm_query')
        self.headers = self.get_header()
        self.token, self.region_ticket = self.__get_token_and_ticket()
        self.cookies = self.get_cookies()
        self.form = self.get_form()
        self.url = self.get_url()

    def get_cookies(self):
        return {'token':self.token, 'region_ticket': self.region_ticket}

    def get_form(self):
        r = get_dict('form') if not self.params_file_name else get_dict(self.params_file_name)
        r['token'] = self.token
        return r

    def get_header(self):
        r = get_dict('comm_header')
        r['host'] = ks_host
        return r

    def get_url(self):
        url = 'http://{host}{api}?{comm_query}'.format(
            host=ks_host,
            api=self.api,
            comm_query=self.__get_comm_query()
        )
        return url

    def __get_comm_query(self):
        return '&'.join(self.comm_query)

    def __get_token_and_ticket(self):
        l = self.headers['Cookie'].split(';')
        token, ticket = list(map(lambda x: x.split('=')[1], l))
        return token, ticket
